package org.genntii.warehousesystem.filter;

import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.genntii.warehousesystem.common.JwtProperties;
import org.genntii.warehousesystem.security.DBEmployeeManager;
import org.genntii.warehousesystem.security.DBUserManager;
import org.genntii.warehousesystem.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
public class JWTAuthorizationFilter extends OncePerRequestFilter {

    @Resource
    private JwtProperties jwtProperties;

    @Resource
    private DBUserManager userManager;

    @Resource
    private DBEmployeeManager employeeManager;
    @Qualifier("filterChain")


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {

        if (request.getServletPath().contains("/user/login") ||
                request.getServletPath().contains("/user/register")){
            chain.doFilter(request,response);
            return;
        }
        final String requestTokenHeader = request.getHeader("Authorization");
        final String clientType = request.getHeader("Client-Type");

        if (requestTokenHeader==null){
            chain.doFilter(request,response);
            return;
        }

        Claims claims = null;
        if (clientType.equals("user")){
            claims = JwtUtil.parseJWT(jwtProperties.getSecretKey(),requestTokenHeader);
            int id = (int) claims.get("id");
            String username = (String) claims.get("username");

            if (id!=0 && username != null && SecurityContextHolder.getContext().getAuthentication() == null){

                UserDetails userDetails = userManager.loadUserByUsername(username);
                System.out.println(userDetails.getAuthorities());

                UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
                        userDetails,null,userDetails.getAuthorities());
                authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                SecurityContextHolder.getContext().setAuthentication(authToken);

                request.setAttribute("id",id);

            }
        } else if (clientType.equals("admin")) {
            claims = JwtUtil.parseJWT(jwtProperties.getEmployeeSecretKey(),requestTokenHeader);
            int id = (int) claims.get("id");
            String username = (String) claims.get("username");

            if (id!=0 && username != null && SecurityContextHolder.getContext().getAuthentication() == null){

                UserDetails userDetails = employeeManager.loadUserByUsername(username);
                System.out.println(userDetails.getAuthorities());

                System.out.println(userDetails.getAuthorities());

                UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
                        userDetails,null,userDetails.getAuthorities());
                authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                SecurityContextHolder.getContext().setAuthentication(authToken);

                request.setAttribute("id",id);

            }
        }

        chain.doFilter(request,response);

    }
}
